//@version=6
indicator("IntradayAFL", shorttitle="IntradayAFL", overlay=true, max_labels_count=500, max_lines_count=500)

// ───── Table Position Setting ─────
tablePosition = input.string("Bottom Right", "Table Position", options=["Top Right", "Top Left", "Bottom Right", "Bottom Left"])
tblPos = switch tablePosition
    "Top Right" => position.top_right
    "Top Left" => position.top_left
    "Bottom Right" => position.bottom_right
    "Bottom Left" => position.bottom_left

// ───── Indicator Toggles ─────
useADX   = input.bool(true, "Use ADX")
useRSI   = input.bool(true, "Use RSI")
usePA    = input.bool(true, "Use Price Action")
useVSA   = input.bool(true, "Use VSA")
useMTF   = input.bool(true, "Use Multi-Timeframe Confirmation")

// ───── Internal Settings ─────
atrPeriod   = 21
factor      = 3.6
adxLength   = 14
adxThresh   = 20
rsiLength   = 14
rsiOB       = 70
rsiOS       = 30
mtfTF       = input.timeframe("15", "MTF Timeframe")

// ───── Supertrend Core ─────
[st, dir] = ta.supertrend(factor, atrPeriod)
longTrend  = dir > 0
shortTrend = dir < 0

plot(longTrend ? st : na, "Up Trend", color.new(color.green, 0), 2)
plot(shortTrend ? st : na, "Down Trend", color.new(color.red, 0), 2)

mid = (open + close) / 2
fill(plot(longTrend ? mid : na, display=display.none), plot(longTrend ? st : na, display=display.none), color.new(color.green, 90))
fill(plot(shortTrend ? mid : na, display=display.none), plot(shortTrend ? st : na, display=display.none), color.new(color.red, 90))

// ───── Filter Calculations ─────
upMove   = high - high[1]
downMove = low[1] - low
plusDM   = na(upMove) or upMove < 0 or upMove < downMove ? 0 : upMove
minusDM  = na(downMove) or downMove < 0 or downMove < upMove ? 0 : downMove
trur     = ta.rma(ta.tr(true), adxLength)
plusDI   = 100 * ta.rma(plusDM, adxLength) / trur
minusDI  = 100 * ta.rma(minusDM, adxLength) / trur
dx       = 100 * math.abs(plusDI - minusDI) / (plusDI + minusDI)
adxVal   = ta.rma(dx, adxLength)
adxCond  = not useADX or adxVal > adxThresh

rsi = ta.rsi(close, rsiLength)
rsiCondBuy = not useRSI or rsi < rsiOB
rsiCondSell = not useRSI or rsi > rsiOS

hh = high > high[1] and high[1] > high[2]
ll = low < low[1] and low[1] < low[2]
paCondBuy = not usePA or hh
paCondSell = not usePA or ll

volAvg = ta.sma(volume, 20)
spread = high - low
spreadAvg = ta.sma(spread, 20)
vsaCondBuy = not useVSA or (volume > volAvg and spread > spreadAvg)
vsaCondSell = not useVSA or (volume > volAvg and spread > spreadAvg)

[stHTF, dirHTF] = request.security(syminfo.tickerid, mtfTF, ta.supertrend(factor, atrPeriod))
mtfCondBuy = not useMTF or dirHTF > 0
mtfCondSell = not useMTF or dirHTF < 0

// ───── Entry Signals ─────
crossUp  = ta.crossover(close, st)
crossDn  = ta.crossunder(close, st)

buySignalBase  = barstate.isconfirmed and crossUp
sellSignalBase = barstate.isconfirmed and crossDn

buySignal  = buySignalBase and adxCond and rsiCondBuy and paCondBuy and vsaCondBuy and mtfCondBuy
sellSignal = sellSignalBase and adxCond and rsiCondSell and paCondSell and vsaCondSell and mtfCondSell

plotshape(buySignal, title="Buy", location=location.belowbar, color=color.green, style=shape.triangleup, size=size.small)
plotshape(sellSignal, title="Sell", location=location.abovebar, color=color.red, style=shape.triangledown, size=size.small)

if buySignal
    label.new(bar_index, low, "Buy\n₹" + str.tostring(close, "#.##"), style=label.style_label_up, color=color.green, textcolor=color.white, size=size.small)
if sellSignal
    label.new(bar_index, high, "Sell\n₹" + str.tostring(close, "#.##"), style=label.style_label_down, color=color.red, textcolor=color.white, size=size.small)

// ───── Trade State ─────
varip int tradeDir = 0
varip float entryPrice = na
varip float targetPrice1 = na
varip float targetPrice2 = na
varip float targetPrice3 = na
varip float trailSL = na
varip float maxPL = 0.0

var bool tgt1Hit = false
var bool tgt2Hit = false
var bool tgt3Hit = false
var bool slHit   = false

atrVal = ta.atr(atrPeriod)

if buySignal or sellSignal
    tradeDir      := buySignal ? 1 : -1
    entryPrice    := close
    targetPrice1  := entryPrice + tradeDir * atrVal * 2.5
    targetPrice2  := entryPrice + tradeDir * atrVal * 4.5
    targetPrice3  := entryPrice + tradeDir * atrVal * 7.0
    trailSL       := st
    tgt1Hit := false
    tgt2Hit := false
    tgt3Hit := false
    slHit   := false
    maxPL := 0.0

if tradeDir != 0 and not na(entryPrice)
    trailSL := st

    if tradeDir == 1
        tgt1Hit := tgt1Hit or high >= targetPrice1
        tgt2Hit := tgt2Hit or high >= targetPrice2
        tgt3Hit := tgt3Hit or high >= targetPrice3
        slHit   := not tgt3Hit and low <= trailSL
    else
        tgt1Hit := tgt1Hit or low <= targetPrice1
        tgt2Hit := tgt2Hit or low <= targetPrice2
        tgt3Hit := tgt3Hit or low <= targetPrice3
        slHit   := not tgt3Hit and high >= trailSL

    currentPL = (close - entryPrice) * tradeDir
    maxPL := math.max(maxPL, currentPL)

    if tgt3Hit or slHit
        tradeDir := 0

// ───── Status and Table ─────
status =
     tgt3Hit ? "TGT3 Hit" :
     tgt2Hit ? "TGT2 Hit" :
     tgt1Hit ? "TGT1 Hit" :
     slHit   ? "SL Hit"   :
     tradeDir != 0 ? "Call Open" : "—"

statusColor = status == "SL Hit" ? color.red :
              status == "Call Open" ? color.orange :
              status == "TGT1 Hit" or status == "TGT2 Hit" or status == "TGT3 Hit" ? color.lime : color.white

// ───── Horizontal Stats Table ─────
var table statsTbl = table.new(tblPos, 8, 2, frame_width=1, frame_color=color.white, border_color=color.white, bgcolor=color.new(color.black, 30))

f_show(v, fmt) => na(v) ? "—" : str.tostring(v, fmt)

if barstate.islast
    bg = color.new(color.rgb(25, 25, 25), 10)
    colPL = maxPL >= 0 ? color.lime : color.red

    table.cell(statsTbl, 0, 0, "Entry", text_color=color.white, bgcolor=bg, text_size=size.small)
    table.cell(statsTbl, 1, 0, "TGT1", text_color=color.white, bgcolor=bg, text_size=size.small)
    table.cell(statsTbl, 2, 0, "TGT2", text_color=color.white, bgcolor=bg, text_size=size.small)
    table.cell(statsTbl, 3, 0, "TGT3", text_color=color.white, bgcolor=bg, text_size=size.small)
    table.cell(statsTbl, 4, 0, "Trail SL", text_color=color.white, bgcolor=bg, text_size=size.small)
    table.cell(statsTbl, 5, 0, "Max P/L", text_color=color.white, bgcolor=bg, text_size=size.small)
    table.cell(statsTbl, 6, 0, "Status", text_color=color.white, bgcolor=bg, text_size=size.small)
    table.cell(statsTbl, 7, 0, "Dir", text_color=color.white, bgcolor=bg, text_size=size.small)

    table.cell(statsTbl, 0, 1, f_show(entryPrice, "#.##"), text_color=color.white, bgcolor=bg, text_size=size.small)
    table.cell(statsTbl, 1, 1, f_show(targetPrice1, "#.##"), text_color=color.white, bgcolor=bg, text_size=size.small)
    table.cell(statsTbl, 2, 1, f_show(targetPrice2, "#.##"), text_color=color.white, bgcolor=bg, text_size=size.small)
    table.cell(statsTbl, 3, 1, f_show(targetPrice3, "#.##"), text_color=color.white, bgcolor=bg, text_size=size.small)
    table.cell(statsTbl, 4, 1, f_show(trailSL, "#.##"), text_color=color.white, bgcolor=bg, text_size=size.small)
    table.cell(statsTbl, 5, 1, f_show(maxPL, "#.##") + " pts", text_color=colPL, bgcolor=bg, text_size=size.small)
    table.cell(statsTbl, 6, 1, status, text_color=statusColor, bgcolor=bg, text_size=size.small)
    table.cell(statsTbl, 7, 1, tradeDir == 1 ? "Buy" : tradeDir == -1 ? "Sell" : "-", text_color=color.white, bgcolor=bg, text_size=size.small)

// ───── Target Lines ─────
plot(tradeDir != 0 ? targetPrice1 : na, "TGT1", color=color.teal, linewidth=1, style=plot.style_linebr)
plot(tradeDir != 0 ? targetPrice2 : na, "TGT2", color=color.orange, linewidth=1, style=plot.style_linebr)
plot(tradeDir != 0 ? targetPrice3 : na, "TGT3", color=color.fuchsia, linewidth=1, style=plot.style_linebr)
plot(tradeDir != 0 ? trailSL : na, "Trailing SL", color=color.gray, linewidth=1, style=plot.style_linebr)

// ───── Alerts ─────
alertcondition(buySignal, title="IAFL Buy", message="Filtered BUY — {{ticker}} @ {{close}}")
alertcondition(sellSignal, title="IAFL Sell", message="Filtered SELL — {{ticker}} @ {{close}}")
